package com.fresh.auth0;

import java.io.UnsupportedEncodingException;

import com.fresh.auth0.algorithms.Algorithm;
import com.fresh.auth0.exceptions.JWTCreationException;
import com.fresh.auth0.exceptions.JWTDecodeException;
import com.fresh.auth0.exceptions.JWTVerificationException;
import com.fresh.auth0.interfaces.DecodedJWT;
import com.fresh.utils.DateTimeUtil;

/**
 * 支持算法
 * HS256 	HMAC256 	HMAC with SHA-256
HS384 	HMAC384 	HMAC with SHA-384
HS512 	HMAC512 	HMAC with SHA-512
RS256 	RSA256 	RSASSA-PKCS1-v1_5 with SHA-256
RS384 	RSA384 	RSASSA-PKCS1-v1_5 with SHA-384
RS512 	RSA512 	RSASSA-PKCS1-v1_5 with SHA-512
ES256 	ECDSA256 	ECDSA with curve P-256 and SHA-256
ES384 	ECDSA384 	ECDSA with curve P-384 and SHA-384
ES512 	ECDSA512 	ECDSA with curve P-521 and SHA-512
 * @author gaonan
 */
public class MainTest {

	private static final String secret="secret";
	
	public static void main(String[] args) {
		String token=null;
		try {
		     token = JWT.create()
		        .withIssuer("auth0")
		        .withExpiresAt(DateTimeUtil.addSeconds(DateTimeUtil.getSystemDate(), 10)) //5秒过期时间
		        .withClaim("token", "token")
		        .sign(Algorithm.HMAC256(secret));
		} catch (JWTCreationException exception){
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		System.out.println("token["+token+"]");
		
		try {
		    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
		        .withIssuer("auth0")
		        //    .acceptLeeway(1)   //1 sec for nbf and iat
			     //.acceptExpiresAt(5) //5秒过期时间
					.build(); // Reusable verifier instance
		    DecodedJWT jwt = verifier.verify(token);
		    System.out.println(DateTimeUtil.formatDateTimetoString(jwt.getExpiresAt()));
		} catch (JWTVerificationException exception){
		    //Invalid signature/claims
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		try {
		    JWT jwt = JWT.decode(token);
		    String algorithm = jwt.getAlgorithm();
		    String type = jwt.getType();
		    String contentType = jwt.getContentType();
		    String keyId = jwt.getKeyId();
		} catch (JWTDecodeException exception){
		    //Invalid token
		}
	}
	
}
